package com.hmall.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.feign.client.ItemClient;
import com.hmall.feign.dto.Item;
import com.hmall.feign.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;

import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 黎明 on 2023/1/7
 */
@Service
public class SearchServiceImpl implements ISearchService {
    //定义全局静态产量索引库名“hmall_item”
    public static final String INDEX_NAME = "hmall_item";

    //注入RestHighLevelClient对象
    @Autowired
    private RestHighLevelClient highLevelClient;

    //定义ObjectMapper用于json与java对象转换
    private final ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private ItemClient itemClient;

    //自动补全
    @Override
    public List<String> suggestion(String key) {
        try {
            SearchRequest request = new SearchRequest(INDEX_NAME);

            request.source().suggest(
                    new SuggestBuilder().addSuggestion("itemSuggestion",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(key).skipDuplicates(true).size(10))
            );

            SearchResponse response = highLevelClient.search(request, RequestOptions.DEFAULT);

            ArrayList<String> resultList = new ArrayList<>();

            Suggest suggest = response.getSuggest();

            CompletionSuggestion itemSuggestion = suggest.getSuggestion("itemSuggestion");

            List<CompletionSuggestion.Entry.Option> options = itemSuggestion.getOptions();

            for (CompletionSuggestion.Entry.Option option : options) {
                resultList.add(option.getText().toString());
            }
            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //动态过滤条件
    @Override
    public Map<String, List<String>> filters(RequestParams params) {

        try {
            SearchRequest request = new SearchRequest(INDEX_NAME);

            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            if (StringUtils.isNotEmpty(params.getKey())) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("all", params.getKey()));
            } else {
                boolQueryBuilder.must(QueryBuilders.matchAllQuery());
            }

            //判断查询条件参数category是否有效
            if (StringUtils.isNotEmpty(params.getCategory())) {
                boolQueryBuilder.filter(QueryBuilders
                        .termQuery("category", params.getCategory()));
            }
            //判断查询条件参数brand是否有效
            if (StringUtils.isNotEmpty(params.getBrand())) {
                boolQueryBuilder.filter(QueryBuilders
                        .termQuery("brand", params.getBrand()));
            }
            //判断查询条件参数maxPrice和minPrice是否有效
            if (params.getMaxPrice() != null && params.getMinPrice() != null) {
                boolQueryBuilder.filter(QueryBuilders
                        .rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
            }

            request.source().query(boolQueryBuilder);

            request.source().size(0);

            request.source().aggregation(AggregationBuilders
                    .terms("brandAgg").field("brand").size(100));
            request.source().aggregation(AggregationBuilders
                    .terms("categoryAgg").field("category").size(100));

            SearchResponse response = highLevelClient.search(request, RequestOptions.DEFAULT);

            Map<String, List<String>> map = new HashMap<>();

            if (response.getAggregations() != null) {
                List<String> categoryList = getKeyListFromAggName(response, "categoryAgg");
                List<String> brandList = getKeyListFromAggName(response, "brandAgg");
                map.put("category", categoryList);
                map.put("brand", brandList);
            }

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //商品搜索
    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        if (params.getPage() == null) params.setPage(1);
        if (params.getSize() == null) params.setSize(20);

        try {
            SearchRequest request = new SearchRequest(INDEX_NAME);

            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            if (StringUtils.isNotEmpty(params.getKey())) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("all", params.getKey()));
            } else {
                boolQueryBuilder.must(QueryBuilders.matchAllQuery());
            }
            boolQueryBuilder.filter(QueryBuilders
                    .termQuery("status", 1));

            //判断查询条件参数category是否有效
            if (StringUtils.isNotEmpty(params.getCategory())) {
                boolQueryBuilder.filter(QueryBuilders
                        .termQuery("category", params.getCategory()));
            }
            //判断查询条件参数brand是否有效
            if (StringUtils.isNotEmpty(params.getBrand())) {
                boolQueryBuilder.filter(QueryBuilders
                        .termQuery("brand", params.getBrand()));
            }
            //判断查询条件参数maxPrice和minPrice是否有效
            if (params.getMaxPrice() != null && params.getMinPrice() != null) {
                params.setMinPrice(params.getMinPrice() * 100);
                params.setMaxPrice(params.getMaxPrice() * 100);
                boolQueryBuilder.filter(QueryBuilders
                        .rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
            }


            //将查询条件传过去
            request.source().trackTotalHits(true).query(boolQueryBuilder);

            //计算分页起始位置
            int from = (params.getPage() - 1) * params.getSize();
            // int from = (1 - params.getPage()) * params.getSize();

            //设置查询分页from和size
            request.source().from(from).size(params.getSize());

            //设置高亮查询字段
            request.source().highlighter(new HighlightBuilder().field("name")
                    .requireFieldMatch(false));

            //广告加分 置顶
            request.source().query(new FunctionScoreQueryBuilder(boolQueryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders
                            .termQuery("isAD", true), ScoreFunctionBuilders
                            .weightFactorFunction(10))
            }).boostMode(CombineFunction.SUM));

            // ES分数排序，防止算分失效
            // request.source().sort(SortBuilders.fieldSort("_score").order(SortOrder.DESC));

            if (org.springframework.util.StringUtils.hasLength(params.getSortBy()) && !"default".equals(params.getSortBy())) {
                // 非默认排序
                request.source().sort(SortBuilders.fieldSort(params.getSortBy()).order(SortOrder.DESC));
            }

            //解除getHits一次只能1w
            // request.source().trackTotalHits(true).query(QueryBuilders.matchAllQuery()).size(20);

            //执行搜索，获取结果
            SearchResponse response = highLevelClient.search(request, RequestOptions.DEFAULT);

            //封装结果并返回
            SearchHits searchHits = response.getHits();

            //获取总记录数
            long total = searchHits.getTotalHits().value;
            System.out.println(response.getHits().getTotalHits().value);

            //遍历获取文档集合数据
            //定义集合List<ItemDoc>收集数据
            List<ItemDoc> itemDocList = new ArrayList<>();
            for (SearchHit searchHit : searchHits) {
                //获取每个文档的json数据
                String json = searchHit.getSourceAsString();
                //son转换为ItemDoc对象
                ItemDoc itemDoc = mapper.readValue(json, ItemDoc.class);
                //替换高亮内容
                HighlightField highlightField = searchHit.getHighlightFields().get("name");


                if (highlightField != null) {
                    itemDoc.setName(highlightField.getFragments()[0].toString());
                }
                //将itemDoc对象添加到集合中
                itemDocList.add(itemDoc);
            }

            //数据返回
            return new PageDTO<>(total, itemDocList);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //动态条件过滤---副
    private List<String> getKeyListFromAggName(SearchResponse response, String aggName) {
        Terms terms = response.getAggregations().get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> keyList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            keyList.add(key);
        }
        return keyList;
    }


    //获取数据库数据更新到ES里面
    @Override
    public void insertById(Long id) {

        try {
            //1.获取数据库数据 Item对象
            Item item = itemClient.getItemById(id);

            //2.将Item封装到ItemDoc中
            ItemDoc itemDoc = new ItemDoc(item);

            //3.创建 IndexRequest 请求对象，并构建 DSL 添加后修改文档命令
            //3.1 构建添加文档命令,格式为：POST item/_doc/id
            IndexRequest indexRequest = new IndexRequest(INDEX_NAME).id(item.getId().toString());

            //5.2 将itemDoc对象转换为json字符串
            String json = mapper.writeValueAsString(itemDoc);

            //5.3 继续构建添加文档命令填充文档数据，格式为：POST item/_doc/id{文档数据}
            indexRequest.source(json, XContentType.JSON);

            //6.执行添加文档命令并获取返回结果对象
            highLevelClient.index(indexRequest, RequestOptions.DEFAULT);

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    //删除ES的文档数据
    @Override
    public void deleteById(Long id) {
        try {
            //1.构建删除文档请求对象
            DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME).id(id.toString());
            //3.执行删除
            highLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
